import pygame
from pygame.sprite import Sprite
from pygame.transform import scale
from pytmx import TiledObjectGroup, TiledImageLayer, load_pygame
from pygame import KEYDOWN, K_KP_ENTER, QUIT
#关卡选择页
#获得关卡数字
def init_number_image():
    number_image = pygame.image.load("../resources/images/level/number.png")
    number_image_list = []
    y = 0
    for row in range(0, 4):
        x = 0
        for col in range(0, 3):
            image = number_image.subsurface(x, y, 179, 170)
            number_image_list.append(image)
            x += 179
        y += 170
    return number_image_list
#更新关卡页
def menu():
    screen = pygame.display.set_mode((1440, 900))
    map_data = load_pygame("../resources/choice_level.tmx")
    number_group = pygame.sprite.Group()
    number_images = init_number_image()
    for layer in map_data.visible_layers:
        if isinstance(layer, TiledObjectGroup):
            if layer.name != "level":
                continue
            for obj in layer:
                number_sprite = Sprite()
                name = obj.name
                temp = name.split('-')
                no = int(temp[1])
                no -= 1
                image = number_images[no]
                scale_image = scale(image, (60, 60))
                number_sprite.image = scale_image
                number_sprite.rect = pygame.Rect(obj.x, obj.y, 60, 60)
                number_sprite.no = no + 1
                number_group.add(number_sprite)
            number_group = number_group
        elif isinstance(layer, TiledImageLayer):
            menu_background = pygame.image.load("../resources/images/level/" + layer.image_name).convert()
            menu_background = pygame.transform.scale(menu_background,
                                                           (int(menu_background.get_width() * 1),
                                                            int(menu_background.get_height() * 1)))

    pygame.display.set_caption('AngryBirds')

    # 背景音乐
    song1 = '../resources/sounds/angry-birds.ogg'
    pygame.mixer.music.load(song1)
    pygame.mixer.music.play(-1)

    while True:
        #监听是否按下，按下返回关卡数字
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            for item in number_group:
                if item.rect.collidepoint(mouse_x, mouse_y):
                    return item.no
        screen.blit(menu_background, (0, 0))
        number_group.draw(screen)
        pygame.display.update()
